package vip.zhenzicheng.nettyadv.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.ReadTimeoutHandler;
import vip.zhenzicheng.nettyadv.cryocodec.KryoDecoder;
import vip.zhenzicheng.nettyadv.cryocodec.KryoEncoder;
import vip.zhenzicheng.nettyadv.server.asyncpro.DefaultTaskProcessor;

/**
 * @author zhenzicheng
 * @date 2022-06-13 21:48
 */
public class ServerInit extends ChannelInitializer<SocketChannel> {

  @Override
  protected void initChannel(SocketChannel channel) throws Exception {
    // 性能统计
    // channel.pipeline().addLast(new MetricsHandler());

    // 解决粘包半包
    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
    channel.pipeline().addLast(new LengthFieldPrepender(2));

    // 序列化相关
    channel.pipeline().addLast(new KryoDecoder());
    channel.pipeline().addLast(new KryoEncoder());

    // 处理心跳超时，netty自带的handler
    channel.pipeline().addLast(new ReadTimeoutHandler(15));

    channel.pipeline().addLast(new LoginAuthRespHandler());
    channel.pipeline().addLast(new HeartBeatRespHandler());
    channel.pipeline().addLast(new ServerBusyHandler(new DefaultTaskProcessor()));
  }
}
